package com.helloandroid.paso.ui.mediaplayer;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.os.AsyncTask;

// Downloads ID3v1 tag data asynchronously, creates and returns an ID3Tag object
// Currently only gets the tag information from the first URL in the paramarray
public class ID3v1Downloader extends AsyncTask<String, Void, ID3Tag>{
	
	// Callback interface to pass the data back to the caller class
	private ITagDownloaderCallback callback;

	public ID3v1Downloader(ITagDownloaderCallback callback) {
		this.callback = callback;
	}

	@Override
	protected ID3Tag doInBackground(String... params) {
		byte[] tag = null;
		try {
			tag = getTag(params[0]);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	
		// Create tag object, set fields and return it
		ID3Tag returnTag = new ID3Tag();
		if(tag != null){			
			returnTag.Title = new String(tag, 0, 30).trim();
			returnTag.Artist = new String(tag, 30, 30).trim();
			returnTag.Album = new String(tag, 60, 30).trim();
			returnTag.Year = Integer.parseInt(new String(tag, 90, 4));
		}
		return returnTag;
	}
	
	@Override
	protected void onPostExecute(ID3Tag param){
		
		// Send the tag object back to the caller class
		callback.onSuccess(param);
	}
	
	private byte[] getTag(String url) throws MalformedURLException, IOException{
		URL uri = new URL(url);


		URLConnection conn = uri.openConnection();

		// Get the file size
		int length = conn.getContentLength();
		
		conn = uri.openConnection();

		// Set the Range field in HTTP header to only request the tag information from the file
		conn.setRequestProperty("Range", "bytes=" + (length - 128) + "-");
		
		InputStream stream = conn.getInputStream();

		
		// Read first 3 bytes to check whether the file has an ID3v1 tag
		byte[] tagField = new byte[3];

		stream.read(tagField, 0, 3);
		
		// Check for tag
		if(!(new String(tagField).equalsIgnoreCase("TAG")))
			return null;
		
		// Read the rest of the tag
		byte[] tag = new byte[125];
		
		stream.read(tag, 0, 125);
		
		return tag;
	}
}
